package com.qiyou.service;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.json.JSONArray;

import com.qiyou.dao.factory.DaoFactory;
import com.qiyou.util.DBUtil;
import com.qiyou.util.LogUtil;

/**
 * 我的活动信息
 * 
 * @author 杨 强
 * 
 */
@WebServlet(name = "MyActivityService", urlPatterns = { "/MyActivityService" })
public class MyActivityService extends HttpServlet {
    private static final long serialVersionUID = 1L;
    private static final Logger log = LogUtil
            .getLogger(MyActivityService.class);

    public MyActivityService() {
        super();
    }

    protected void doGet(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }

    protected void doPost(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {
        response.setCharacterEncoding("utf-8");
        response.setContentType("application/json");

        String userID = request.getParameter("id");
        String sql = "select `tb_activity`.acID, userFace, `tb_activity`.userID, acDate, acStartDate, acPlace, `temp_table`.joinedNum, `max` from tb_activity left outer join tb_user_info on `tb_activity`.userID=`tb_user_info`.userID, (select `temp_table1`.acID, count(`temp_table1`.userID) joinedNum from `tb_activity_invitation` `temp_table1` where `temp_table1`.acID in (select `temp_table2`.acID from `tb_activity_invitation` `temp_table2` where `temp_table2`.userID=? and `temp_table2`.aiState=?) group by `temp_table1`.acID) `temp_table` where `temp_table`.acID=`tb_activity`.acID";
        Connection conn = DaoFactory.getDatabase().getConnection();
        List<Map<String, Object>> result = null;
        try {
            result = DBUtil.queryForMap(conn, sql, userID, "R");
        } catch (SQLException e) {
            log.error(e);
        } finally {
            DBUtil.closeConnection(conn);
        }

        JSONArray questionjson = new JSONArray(result);
        String msg = questionjson.toString();
        PrintWriter out = response.getWriter();
        out.print(msg);
        out.flush();
        out.close();

        log.info("用户:" + userID + ",访问了活动列表信息:" + msg);
    }

}
